package org.wpahs.ahn.rssfeed.DB;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import org.wpahs.ahn.rssfeed.MyFeed;
import java.util.ArrayList;
import java.util.List;

/**
 * Class to CRUD on Feed table
 * Created by dgambone on 01/15/2015.
 */
public class DBMyFeed extends FeedsDB {



    public DBMyFeed(Context context) {
        super(context);
    }

    public Boolean isOpen(){
        return this.getReadableDatabase().isOpen();
    }

    public List<MyFeed> GetFeeds(Boolean includeAll){
        List<MyFeed> results = new ArrayList<>();
        if(includeAll){
            MyFeed all = new MyFeed();
            all.setTitle("All");
            all.setId(0);
            results.add(all);

            //Favorites
            MyFeed favorites = new MyFeed();
            favorites.setId(-2);
            favorites.setTitle("Favorites");
            results.add(favorites);

        }
        Cursor cursor = this.getReadableDatabase().query(
                DB.TABLE_NAME,
                new String[] {
                        DB.COLUMN_FEED_ID,
                        DB.COLUMN_TITLE,
                        DB.COLUMN_SUBTITLE,
                        DB.COLUMN_URL,
                        DB.COLUMN_LASTUPDATED,
                        DB.COLUMN_IMAGE
                },
                null,
                null,
                null,null,DB.COLUMN_TITLE + " asc");

        if(cursor != null && cursor.getCount() > 0) {
            while(cursor.moveToNext()) {
                MyFeed feed = new MyFeed();
                feed.setId(cursor.getInt(0));
                feed.setTitle(cursor.getString(1));
                feed.setSubtitle(cursor.getString(2));
                feed.setUrl(cursor.getString(3));
                feed.setLastUpdateFromString(cursor.getString(4));
                feed.setImage(cursor.getString(5));
                results.add(feed);
            }
            cursor.close();
        }

        if(includeAll){
            //Settings
            /*
            MyFeed settings = new MyFeed();
            settings.setId(-1);
            settings.setTitle("Settings");
            results.add(settings);
            */
        }
        return results;
    }


    public int addFeed(MyFeed feed){

        if(!existsByURL(feed.getUrl())) {
            ContentValues cv = toContentValues(feed);
            cv.remove(DB.COLUMN_FEED_ID); // REMOVE
            long id = this.getWritableDatabase().insert(
                    DB.TABLE_NAME,
                    null,
                    cv
            );
            if(id> 0){
                Log.i("FeedSettings", "Created feed " + String.valueOf(id) + " - " + feed.getTitle());
                return ((int) id);
            }else{
                Log.i("FeedSettings-addFeed", "Id was not set");
                return 0;
            }
        }else{
            return 0;
        }
    }

    public MyFeed getFeed(int id){
        MyFeed feed = null;
        Cursor cursor = this.getReadableDatabase().query(
                DB.TABLE_NAME,
                new String[] {
                        DB.COLUMN_FEED_ID,
                        DB. COLUMN_TITLE,
                        DB.COLUMN_SUBTITLE,
                        DB.COLUMN_URL,
                        DB.COLUMN_LASTUPDATED,
                        DB.COLUMN_IMAGE
                },
                DB.COLUMN_FEED_ID + "=?",
                new String[] {String.valueOf(id)},
                null,null,null,null);

        if(cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
                feed = new MyFeed();
                feed.setId(cursor.getInt(0));
                feed.setTitle(cursor.getString(1));
                feed.setSubtitle(cursor.getString(2));
                feed.setUrl(cursor.getString(3));
                feed.setLastUpdateFromString(cursor.getString(4));
                feed.setImage(cursor.getString(5));
            cursor.close();
        }

        return feed;
    }



    public void updateFeed(MyFeed feed){
        ContentValues cv = toContentValues(feed);
        cv.remove(DB.COLUMN_FEED_ID);
        cv.remove(DB.COLUMN_IMAGE); //don't overwrite image.  it's done seperately
        this.getWritableDatabase().update(DB.TABLE_NAME, cv, DB.COLUMN_FEED_ID +"="+feed.getId(), null);
    }

    private boolean existsByURL(String url){

        Cursor cursor = this.getReadableDatabase().query(
                DB.TABLE_NAME,
                new String[] {DB.COLUMN_FEED_ID},
                DB.COLUMN_URL + "=?",
                new String[] {url},
                null,null,null,null);

        if(cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            Log.i("DBMyFeed", url + "already exists (" + String.valueOf(cursor.getInt(0)));
            cursor.close();
            return true;
        }else{
            return false;
        }
    }

    public void deleteFeed(int id){

            String feedId = String.valueOf(id);
            this.getWritableDatabase().delete(
                    DB.TABLE_NAME,
                    DB.COLUMN_FEED_ID + "=?",
                    new String[]{feedId}
            );

            // now clear out the feed Items
            int affected = this.getWritableDatabase().delete(
                    DBFeedItem.DB.TABLE_NAME,
                    DBFeedItem.DB.COLUMN_FEED_ID + "=" +
                            String.valueOf(id),
                    null
            );
            Log.i("DBMyFeed", String.valueOf(affected) + " was deleted.");
    }

    public void clearTable(){
        int rowsDeleted = this.getWritableDatabase().delete(DB.TABLE_NAME,null,null);
        Log.i("DBMyFeed-clearTable",String.valueOf(rowsDeleted) + " rows deleted");
    }

    public ContentValues toContentValues(MyFeed feed){
        ContentValues cv = new ContentValues();
        cv.put(DB.COLUMN_FEED_ID, feed.getId());
        cv.put(DB.COLUMN_TITLE, feed.getTitle());
        cv.put(DB.COLUMN_SUBTITLE, feed.getSubtitle());
        cv.put(DB.COLUMN_URL,feed.getUrl());
        cv.put(DB.COLUMN_LASTUPDATED,feed.getLastUpdatedToString());
        cv.put(DB.COLUMN_IMAGE,feed.getImage());
        return cv;
    }

    public void setTitle(int feedId, String title) throws Exception {
        if(feedId == 0){
            throw new Exception("feedId is required");
        }
        ContentValues cv = new ContentValues();
        cv.put(DB.COLUMN_TITLE,title);
        long recordsUpdated = this.getWritableDatabase().update(
                DB.TABLE_NAME,
                cv,
                DB.COLUMN_FEED_ID + "=?",
                new String[] {String.valueOf(feedId)}
        );
        if (recordsUpdated > 0) {
            if(title != null){
                Log.i("DBMyFeed.setTitle", "Set title for " + feedId + " - " + title);

            }else{
                Log.i("DBMyFeed.setTitle", "Set title for " + feedId + " it's NULL");
            }
        } else {
            Log.i("FeedItem.setTitle", "Id was not set");

        }
    }

    public void setImage(int feedId, String image) throws Exception {
        if(feedId == 0){
            throw new Exception("feedId is required");
        }
        ContentValues cv = new ContentValues();
        cv.put(DB.COLUMN_IMAGE,image);
        long recordsUpdated = this.getWritableDatabase().update(
                DB.TABLE_NAME,
                cv,
                DB.COLUMN_FEED_ID + "=?",
                new String[] {String.valueOf(feedId)}
        );
        if (recordsUpdated > 0) {
            if(image != null){
                Log.i("DBMyFeed.setImage", "Set image for " + feedId + " of size " + image.length());

            }else{
                Log.i("DBMyFeed.setImage", "Set image for " + feedId + " it's NULL");
            }
        } else {
            Log.i("FeedItem.setImage", "Id was not set");

        }
    }
    public String getImage(int feedId){
        Cursor cursor = this.getReadableDatabase().query(
                DB.TABLE_NAME,
                new String[]{DB.COLUMN_IMAGE},
                DB.COLUMN_FEED_ID + "=?",
                new String[]{String.valueOf(feedId)},
                null, null, null, null);

        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            String image = cursor.getString(0);
            cursor.close();
            return image;
        } else {
            return null;
        }
    }


    public abstract class DB{
        public static final String TABLE_NAME = "Feeds";
        public static final String COLUMN_FEED_ID = "feedid";
        public static final String COLUMN_TITLE = "title";
        public static final String COLUMN_SUBTITLE = "subtitle";
        public static final String COLUMN_URL = "url";
        public static final String COLUMN_LASTUPDATED = "lastupdated";
        public static final String COLUMN_IMAGE = "image";


        public static final String SQL_CREATE_TABLE =
                "CREATE TABLE " + TABLE_NAME + " (" +
                        COLUMN_FEED_ID + " INTEGER PRIMARY KEY," +
                        COLUMN_TITLE + " TEXT_TYPE, " +
                        COLUMN_SUBTITLE + " TEXT_TYPE, " +
                        COLUMN_URL + " TEXT_TYPE, " +
                        COLUMN_LASTUPDATED + " TEXT_TYPE," +
                        COLUMN_IMAGE + " TEXT_TYPE" +
                        ")";
    }
}
